#include <SchedulerLog.h>
#include <csp_debug.h>
#include <csp_macros.h>
#include <csp_shared_types.h>
#include <csp_protocol_msg.h>

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <Scheduler.h>
#include <pthread.h>
#include <map>

using namespace std;


SchedulerLog::SchedulerLog()
{
	if( pthread_mutex_init(&chan_log_lock, NULL) ){
		perror("channel log could not init lock.");
		exit(-1);
	}
	//log = (char*) calloc(MAX_SIZE, sizeof(char));
	log = (sched_log_item_t*) calloc(MAX_SCH_LOG_SIZE, sizeof(sched_log_item_t));
	i=0;
}

SchedulerLog::~SchedulerLog()
{
}

void SchedulerLog::Print()
{
	int t;
	for(t=0; t <= i; t++){

		printf("size=%i, pid=%i, slot=%i, pos=%i, action=%s\n",
			(int) log[t].size, log[t].pid, (int) log[t].slot, log[t].pos,
			log[t].decrement ? "decrement" : "incrementt");
	}
}


void SchedulerLog::Increment(ProcessComposition* p, int pos)
{
	pthread_mutex_lock (&chan_log_lock);
	if(MAX_SCH_LOG_SIZE != i){
		log[i+1].pos = pos;
		log[i+1].decrement = false;
		log[i+1].pid = p->spid;
		log[i+1].slot = p->GetPCB()->slot;
		log[i+1].size = log[i].size+1;
		i++;
	}
	pthread_mutex_unlock (&chan_log_lock);
}


void SchedulerLog::Decrement(ProcessComposition* p, int pos)
{
	pthread_mutex_lock (&chan_log_lock);
	if(MAX_SCH_LOG_SIZE != i){
	log[i+1].decrement = true;
	log[i+1].pos = pos;
	log[i+1].pid = p->spid;
	log[i+1].slot = p->GetPCB()->slot;
	log[i+1].size = log[i].size-1;
	i++;
	}
	pthread_mutex_unlock (&chan_log_lock);
}




SchedulerLog* SchedulerLog::pinstance = 0;// initialize pointer

	SchedulerLog* 
SchedulerLog::Instance () 
{
	if (pinstance == 0)  // is it the first call?
	{  
		pinstance = new SchedulerLog(); // create sole instance
	}
	return pinstance; // address of sole instance
}


